package com.bocloud.cmp.driver.providers.os;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.openstack4j.model.compute.HostResource;
import org.openstack4j.model.compute.ext.Hypervisor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.convertor.BeanConvert;
import com.bocloud.cmp.driver.convertor.os.ConvertHyperV;
import com.bocloud.cmp.driver.providers.HyperVDriver;
import com.bocloud.cmp.model.HostModel;
import com.bocloud.cmp.model.HostPerfModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;

public class OSHyperVDriver extends OSDriver implements HyperVDriver {

	private static final Logger logger = LoggerFactory.getLogger(OSHyperVDriver.class);

	public OSHyperVDriver() {
		super();
	}

	public OSHyperVDriver(String endpoint, String username, String password, String tenant, String domain,
			String project, Version version) {
		super(endpoint, username, password, tenant, domain, project, version);
	}

	@Override
	public BsmResult list() {
		if (!this.accessable()) {
			logger.error(this.getError());
			return new BsmResult(false, this.getError());
		}
		List<? extends Hypervisor> hyperVs = this.getClient().compute().hypervisors().list();
		if (null == hyperVs || hyperVs.isEmpty()) {
			hyperVs = new ArrayList<>();
		}
		BeanConvert<HostModel, Hypervisor> convertHyperV = new ConvertHyperV();
		return new BsmResult(true, convertHyperV.convertList(hyperVs), "success");
	}

	@Override
	public BsmResult listPerf() {
		List<HostPerfModel> hostPerfModel = Lists.newArrayList();
		List<? extends Hypervisor> hypervs = this.getClient().compute().hypervisors().list();
		for (Hypervisor hyper : hypervs) {
			List<? extends HostResource> hostResources = this.getClient().compute().host()
					.hostDescribe(hyper.getHypervisorHostname());
			hostPerfModel.add(convert(hostResources));
		}
		return new BsmResult(true, hostPerfModel, "success");
	}

	/**
	 * 转化参数
	 * 
	 * @param hostResource
	 * @return
	 */
	private HostPerfModel convert(List<? extends HostResource> hostResources) {
		HostPerfModel hostPerfModel = new HostPerfModel();
		if (null == hostResources) {
			return null;
		}
		for (HostResource hostResource : hostResources) {
			if (hostResource.getProject().equalsIgnoreCase("(total)")) {
				hostPerfModel.setCpuTotal(hostResource.getCpu());
				hostPerfModel.setDiskTotal(hostResource.getDiskInGb());
				hostPerfModel.setMemTotal(hostResource.getMemoryInMb());
				hostPerfModel.setHostName(hostResource.getHost());
			} else if (hostResource.getProject().equalsIgnoreCase("(used_now)")) {
				hostPerfModel.setCpuUsed(hostResource.getCpu());
				hostPerfModel.setDiskUsed(hostResource.getDiskInGb());
				hostPerfModel.setMemUsed(hostResource.getMemoryInMb());
			}
			hostPerfModel.setGmtCreate(new Date());
		}
		return hostPerfModel;
	}
}
